import requests
import re
import glob
import threading
import os

class DownLoad:
    
    def __init__(self,
                 url='http://audio.xmcdn.com/group47/M08/FA/A4/wKgKk1uYvdmzgjpMABWn2QTdgLc781.m4a',
                 start_num=0,
                 end_num=None,
                 dir_name='content',
                 ):
        self.dir_name=dir_name
        self.start_num=start_num
        self.end_num=end_num
        self.url=url
        self.request_headers=self.request_headers()
        
        self.num=int(self.xz())
    def request_headers(self):
        headers={
            
                'Accept': '*/*',
                'Accept-Encoding': 'identity;q=1, *;q=0',
                'Accept-Language': 'zh-CN,zh;q=0.9',
                'Connection': 'keep-alive',
                'Host': 'audio.xmcdn.com',
                'Range': 'bytes={}-{}'.format(self.start_num,self.end_num),
                'Referer': '{}'.format(self.url),
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36',
            }
        return headers
    def xz(self):
        headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36'}
        res=requests.get(self.url,headers=headers)
        head=res.headers['Content-Length']
        #print(head)
        return head
    def xia(self,arg):
        #print(self.request_headers)
        cont=requests.get(self.url,headers=self.request_headers)
        if not glob.glob(self.dir_name):
            os.mkdir(self.dir_name)
        with open('{}/{}.con'.format(self.dir_name,arg),'wb') as f:
            f.write(cont.content)

class XunLei(DownLoad,threading.Thread):
    def __init__(self,
                 url='http://audio.xmcdn.com/group47/M08/FA/A4/wKgKk1uYvdmzgjpMABWn2QTdgLc781.m4a',
                 start_num=0,
                 end_num=None,
                 dir_name='content',
                 file_name='file',
                 arg=5,
                 ):
        threading.Thread.__init__(self)
        self.down=DownLoad()
        self.url=url
        self.start_num=start_num
        self.end_num=end_num
        self.dir_name=dir_name
        self.arg=arg
        self.num=int(self.xz())
        self.pool=enumerate(iter(self.xian_pool()))
        
    def xian_pool(self):
        
        xian_list=[]
        for i in range(0,self.num,100000):
            xian_list.append(i)
        xian_list.append(self.num)
        pool_list=[]
        for i in range(len(xian_list)-1):
            pool_list.append((xian_list[i],xian_list[i+1]))
        print(pool_list)
        return pool_list

    def merge(self):
        
        merge_list=glob.glob(DownLoad().dir_name+'/*')
        with open('{}.m4a'.format('merge'),'wb') as f:
            for i in merge_list:
                #print(i)
                with open(i,'rb') as ff:
                    f.write(ff.read())
                    
    def save(self):
        if self.num != None:
            while True:
                print('有{}条线程'.format(threading.active_count()))
                print('\n')
                try:
                    info=next(self.pool)
                except StopIteration:
                    if threading.active_count()<3:
                        break
                    elif threading.active_count() == 3:
                        print('线程还有3个')
                        self.merge()
                        print('合并完成')
                        break
                    else:
                        break
                else:
                    self.down.xia(info[0])
                    if threading.active_count() < self.arg:
                        self.xian_cheng()
        else:
            print('文件错误')
            pass
        
    def xian_cheng(self):
        threading.Thread(target=self.save).start()
                    

if __name__ == '__main__':
    
    url=input('请输入要下载的链接:')
    number=DownLoad(url=url).xz()
    print('文件的大小为{},每个线程下载100000个字节'.format(number))
    arg=int(input('请输入线程数：'))
    XunLei(arg=arg).xian_cheng()

       
